#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:ssoUserService.py
# author:PigKnight
# datetime:2022/2/22 21:40
# software: PyCharm

from ..models import db
from ..models.ssoUserModel import SsoUser
from ..utils.aes_encrypt_decrypt import AESEncryptDecrypt
from ..utils.rsa_encryption_decryption import RSAEncryptionDecryption
from ..utils.response_code import RET, error_map_EN
from ..utils.loggings import loggings
from ..utils import commons

class SsoUserService(SsoUser):
    @classmethod
    def login(cls, **kwargs):
        # 接收参数
        user_account = kwargs.get('account')
        user_password = kwargs.get('password')

        filter_list = [cls.account == AESEncryptDecrypt.encrypt(user_account)]

        # 从数据库根据登录账号查询用户对象
        try:
            user_info = db.session.query(cls).filter(*filter_list).first()
        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.LOGINERR, 'message': error_map_EN[RET.LOGINERR], 'error': "数据库连接异常，登录失败"}

        # 验证用户是否存在
        if not user_info:
            return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': '用户不存在'}

        user_info_data = commons.query_to_dict(user_info)

        # 校验密码
        try:
            if RSAEncryptionDecryption.decrypt(user_info_data.get('password')) != user_password:
                return {'code': RET.LOGINERR, 'message': error_map_EN[RET.LOGINERR], 'error': "密码错误"}
        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.LOGINERR, 'message': error_map_EN[RET.LOGINERR], 'error': "数据库连接异常，密码查验失败"}

        # 生成token
        from .userTokenService import UserTokenService
        token = UserTokenService.create_token(user_info_data.get('userID'), user_info_data.get('userType'))

        # 通用方法返回的全部用户信息
        user_data = commons.query_to_dict(user_info)

        # 自定义接口返回的信息准备
        user_id = user_data.get('userID')
        user_type = user_data.get('userType')

        back_data = {
            'userID': user_id,
            'userType': user_type,
            'Token': token
        }

        # 根据userType选择查询的表返回相应ID
        # 1--学生 2--教师 3--管理员
        if user_type == 1:
            from ..controller.studentController import StudentController
            student_data = StudentController.get(**{'UserID': user_id})
            if student_data.get('code') == RET.OK and student_data.get('totalCount') > 0:
                back_data['studentID'] = student_data.get('data')[0]['studentID']
        elif user_type == 2:
            from ..controller.teacherController import TeacherController
            teacher_data = TeacherController.get(**{'UserID': user_id})
            if teacher_data.get('code') == RET.OK and teacher_data.get('totalCount') > 0:
                back_data['teacherID'] = teacher_data.get('data')[0]['teacherID']
        elif user_type == 3:
            from ..controller.adminController import AdminController
            admin_data = AdminController.get(**{'UserID': user_id})
            if admin_data.get('code') == RET.OK and admin_data.get('totalCount') > 0:
                back_data['adminID'] = admin_data.get('data')[0]['adminID']

        return {'code': RET.OK, 'message': error_map_EN[RET.OK], "data": back_data}
